package com.example.pharmacy.controller;

import com.example.pharmacy.commen.Constant;
import com.example.pharmacy.model.Cart;
import com.example.pharmacy.model.CartResult;
import com.example.pharmacy.model.Result;
import com.example.pharmacy.model.UserInfo;
import com.example.pharmacy.service.CartService;
import com.example.pharmacy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-25
 * Time: 17:20
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private UserService userService;
    @RequestMapping("/addDrug")
    public Result addDrug(Integer drugId, HttpSession session) {
        String name = (String) session.getAttribute(Constant.SESSION_USER_KEY);
        UserInfo userInfo = userService.selectUserByName(name);
        Cart cart = new Cart();
        cart.setUserId(userInfo.getUserId());
        cart.setDrugId(drugId);
        Integer ret = cartService.addDrug(cart);
        if (ret != 1) {
            return Result.fail("加入购物车失败");
        }
        return Result.success("");
    }
    @RequestMapping("/getDrugList")
    public Result getDrugList(HttpSession session) {
        String name = (String) session.getAttribute(Constant.SESSION_USER_KEY);
        UserInfo userInfo = userService.selectUserByName(name);
        List<CartResult> cartResults = cartService.getDrugList(userInfo.getUserId());
        if (cartResults == null) {
            return Result.fail("获取购物车失败");
        }
        return Result.success(cartResults);
    }
    @RequestMapping("/updateCart")
    public Result updateCart(Cart cart) {
        if (cart == null) {
            Result.fail("购物车商品信息有误");
        }
        Integer ret = cartService.updateCart(cart);
        if (ret != 1) {
            Result.fail("更新失败");
        }
        return Result.success("");
    }
    @RequestMapping("/bulkOrder")
    public Result bulkOrder(@RequestParam List<Integer> cartIds, HttpSession session) {
        if (cartIds == null || cartIds.size() == 0) {
            return Result.fail("请选择商品再下单!");
        }
        String name = (String) session.getAttribute(Constant.SESSION_USER_KEY);
        UserInfo userInfo = userService.selectUserByName(name);
        Integer ret = cartService.addOrder(cartIds, userInfo.getUserId());
        if (ret <= 0) {
            return Result.fail("下单失败");
        }
        return Result.success("");
    }
}
